<template>
  <div class="wrapper" @scroll="onScrollVal">
    <div :style="globalStyle">
      <div class="h" ref="layer" :style="cptedStyle">
        <div v-for="lv in list" :key="lv.id" class="ln-style">
          <span>No.{{ lv.id }}</span> - <span>{{ lv.words }}</span>
        </div>
      </div>
      <!-- <div class="next-style" :style="{ height: `${hgNetxVal}px` }"></div> -->
    </div>
  </div>
</template>

<script setup>
import * as utils from "@/utils/index.js";
import { computed, nextTick } from "vue";
let bufferVal = 5,
  all = 50,
  visibale = 20;

const layer = ref(null);
const hgVal = ref(0);
const stVal = ref(0);
const cltVal = ref(0);
const translateY = ref(0);
const scrollTop = ref(0);
const lnVal = ref(80);
const hl = ref(utils.listCreate(all));

const cptedStyle = computed(() => {
  const tVal = Math.max(translateY.value, 0);
  return { transform: `translateY(${tVal}px)` };
});

const globalStyle = computed(() => {
  return { height: `${hgVal.value}px` };
});

const list = computed(() => {
  const val = Math.max(stVal.value, 0);
  const end = stVal.value + visibale;
  const finVal = Math.min(end, all);
  return hl.value.slice(val, finVal);
});

onMounted(() => {
  const hg = layer.value.clientHeight;
  cltVal.value = hg;
  console.log(layer.value.clientHeight);
  hgVal.value = hg * (all / visibale);
});

const onScrollVal = (e) => {
  const scrollVal = e.target.scrollTop;
  const isUpScroll = scrollTop.value - scrollVal > 0;
  scrollTop.value = scrollVal;
  const startVal = ~~(scrollVal / lnVal.value);

  if (isUpScroll) {
    if (startVal < stVal.value) {
      stVal.value = startVal - bufferVal;
      translateY.value = stVal.value * lnVal.value;
      console.log("----", scrollVal);
    }
  } else {
    if (startVal >= stVal.value + bufferVal) {
      stVal.value = startVal;
      translateY.value = stVal.value * lnVal.value;
    }
    console.log("startVal", startVal);
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  box-sizing: content-box;
  height: 480px;
  overflow: auto;
  overflow-anchor: none;
  border: 2px solid yellowgreen;
}

.ln-style {
  line-height: 40px;
  height: 80px;
  overflow: hidden;
}
</style>
